package com.ikingtech.platform.service.system.dept.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikingtech.framework.sdk.base.model.PageResult;
import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.department.model.DeptQueryParamDTO;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.dept.entity.DepartmentDO;
import com.ikingtech.platform.service.system.dept.mapper.DeptMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tie yan
 */
@Service
@AllArgsConstructor
@Slf4j
public class DeptService extends ServiceImpl<DeptMapper, DepartmentDO> {

    public String parseFullPath(String parentId, String id) {
        if (Tools.Str.isNotBlank(parentId)) {
            DepartmentDO parentEntity = this.getById(parentId);
            if (null == parentEntity) {
                throw new FrameworkException("parentDeptNotFound");
            }
            if (Tools.Str.isBlank(parentEntity.getFullPath())) {
                return id;
            }
            return parentEntity.getFullPath() + "@" + id;
        } else {
            return id;
        }
    }

    public Boolean exist(String id) {
        return this.baseMapper.exists(Wrappers.<DepartmentDO>lambdaQuery().eq(DepartmentDO::getId, id));
    }

    public PageResult<DepartmentDO> listPage(DeptQueryParamDTO queryParam, List<String> dataScope, String tenantCode) {
        return PageResult.build(this.page(new Page<>(queryParam.getPage(), queryParam.getRows()), this.createQueryWrapper(queryParam, dataScope, tenantCode)));
    }

    public List<String> listIdsByFullPath(String fullPath) {
        return this.listObjs(Wrappers.<DepartmentDO>lambdaQuery()
                .select(DepartmentDO::getId)
                .likeRight(DepartmentDO::getFullPath, fullPath), String.class::cast);
    }

    public Integer getMaxSortOrder(String parentId) {
        List<Number> orders = this.listObjs(Wrappers.<DepartmentDO>lambdaQuery()
                .select(DepartmentDO::getSortOrder)
                .eq(DepartmentDO::getParentId, parentId)
                .orderByDesc(DepartmentDO::getSortOrder), Number.class::cast);
        return Tools.Coll.isBlank(orders) ? 0 : orders.get(0).intValue();
    }

    public <T> List<DepartmentDO> between(Object parentId, T startValue, T endValue) {
        return this.list(Wrappers.<DepartmentDO>query().lambda()
                .eq(DepartmentDO::getParentId, parentId)
                .between(DepartmentDO::getSortOrder, startValue, endValue)
        );
    }

    public List<DepartmentDO> gt(Object parentId, Object value) {
        return this.list(Wrappers.<DepartmentDO>query().lambda()
                .eq(DepartmentDO::getParentId, parentId)
                .gt(DepartmentDO::getSortOrder, value)
                .orderByAsc(DepartmentDO::getSortOrder)
        );
    }

    public List<DepartmentDO> listByFullPaths(List<String> fullPaths) {
        return this.list(Wrappers.<DepartmentDO>lambdaQuery()
                .or(wrapper -> fullPaths.forEach(fullPath -> wrapper.likeRight(DepartmentDO::getFullPath, fullPath))));
    }

    public List<String> listIdsByFullPaths(List<String> fullPaths) {
        if (Tools.Coll.isBlank(fullPaths)) {
            return new ArrayList<>();
        }
        return this.listObjs(Wrappers.<DepartmentDO>lambdaQuery()
                .or(wrapper -> fullPaths.forEach(fullPath -> wrapper.likeRight(DepartmentDO::getFullPath, fullPath))), String.class::cast);
    }

    public List<String> listFullPathByIds(List<String> ids) {
        return this.listObjs(Wrappers.<DepartmentDO>lambdaQuery()
                .select(DepartmentDO::getFullPath)
                .in(DepartmentDO::getId, ids), String.class::cast);
    }

    public List<String> listFullPathAll(String tenantCode) {
        return this.listObjs(Wrappers.<DepartmentDO>lambdaQuery()
                .select(DepartmentDO::getFullPath)
                .eq(DepartmentDO::getTenantCode, tenantCode), String.class::cast);
    }

    public List<DepartmentDO> listSubByFullPaths(List<String> fullPaths) {
        if(Tools.Coll.isBlank(fullPaths)){
            return new ArrayList<>();
        }
        return this.list(Wrappers.<DepartmentDO>lambdaQuery()
                .or(wrapper -> fullPaths.forEach(fullPath -> wrapper.likeRight(DepartmentDO::getFullPath, fullPath)))
                .orderByDesc(DepartmentDO::getCreateTime));
    }

    public List<DepartmentDO> all(List<String> ids, String tenantCode) {
        return this.list(Wrappers.<DepartmentDO>lambdaQuery()
                .in(Tools.Coll.isNotBlank(ids), DepartmentDO::getId, ids)
                .eq(Tools.Str.isNotBlank(tenantCode), DepartmentDO::getTenantCode, tenantCode)
                .orderByDesc(DepartmentDO::getCreateTime));
    }

    public List<DepartmentDO> listByName(String name, String tenantCode) {
        return this.list(Wrappers.<DepartmentDO>lambdaQuery()
                .like(DepartmentDO::getName, name)
                .eq(DepartmentDO::getTenantCode, tenantCode)
                .orderByDesc(DepartmentDO::getCreateTime));
    }

    public List<DepartmentDO> listByParentId(String parentId) {
        return this.list(Wrappers.<DepartmentDO>lambdaQuery()
                .eq(DepartmentDO::getParentId, parentId)
                .orderByDesc(DepartmentDO::getCreateTime));
    }

    public List<DepartmentDO> listByIdAndOrgId(List<String> ids, String orgId) {
        return this.list(Wrappers.<DepartmentDO>lambdaQuery()
                .in(Tools.Coll.isNotBlank(ids), DepartmentDO::getId, ids)
                .like(DepartmentDO::getOrgId, orgId)
                .orderByDesc(DepartmentDO::getCreateTime));
    }

    public List<DepartmentDO> listByCondition(DeptQueryParamDTO queryParam, String tenantCode) {
        return this.list(this.createQueryWrapper(queryParam, new ArrayList<>(), tenantCode));
    }

    private LambdaQueryWrapper<DepartmentDO> createQueryWrapper(DeptQueryParamDTO queryParam, List<String> dataScope, String tenantCode) {
        return Wrappers.<DepartmentDO>lambdaQuery()
                .in(Tools.Coll.isNotBlank(dataScope), DepartmentDO::getId, dataScope)
                .eq(Tools.Str.isNotBlank(tenantCode), DepartmentDO::getTenantCode, tenantCode)
                .like(Tools.Str.isNotBlank(queryParam.getName()), DepartmentDO::getName, queryParam.getName())
                .eq(Tools.Str.isNotBlank(queryParam.getOrgId()), DepartmentDO::getOrgId, queryParam.getOrgId())
                .eq(Tools.Str.isNotBlank(queryParam.getManagerId()), DepartmentDO::getManagerId, queryParam.getManagerId())
                .orderByDesc(DepartmentDO::getCreateTime);
    }

    public void removeByTenantCode(String tenantCode) {
        this.remove(Wrappers.<DepartmentDO>lambdaQuery().eq(DepartmentDO::getTenantCode, tenantCode));
    }

    public List<String> listFullPathByOrgIds(List<String> orgIds) {
        return this.listObjs(Wrappers.<DepartmentDO>lambdaQuery()
                .select(DepartmentDO::getFullPath)
                .in(DepartmentDO::getOrgId, orgIds), String.class::cast);
    }

    public List<String> listIdByName(String name) {
        return this.listObjs(Wrappers.<DepartmentDO>lambdaQuery()
                .select(DepartmentDO::getId)
                .like(DepartmentDO::getName, name), String.class::cast);
    }
}
